// 搜索数据的仓库
import { defineStore } from 'pinia'
import searchApi from '@/api/search'
import { showNotify } from 'vant'

// 声明类型
interface HotData {
  keyword: string
  highlight: number
}

interface HotListData {
  hotKeywordVOList: HotData[]
}

export interface goodsData {
  id: number
  name: string
  listPicUrl: string
  retailPrice: number
  counterPrice: number
}

interface SearchData {
  directlyList: goodsData[]
  categoryL1List: []
}

const useSearchStore = defineStore('search', {
  state() {
    return {
      searchData: {} as SearchData, // 搜索某个关键字获取到的数据（手机）
      lenovoData: [] as string[], // 输入关键字，实时联想到的数据列表
      hotData: {} as HotListData // 热门搜索数据
    }
  },
  actions: {
    // 获取搜索数据
    async getSearchData(keyword: string) {
      try {
        const res = await searchApi.reqGetSearch(keyword)
        this.searchData = res.data
        return 'ok'
      } catch (error) {
        showNotify({ type: 'danger', message: '搜索失败，请重试！' })
        return 'failed'
      }
    },
    // 获取实时联想数据
    async getTimeLenovoData(keywordPrefix: string) {
      try {
        const res = await searchApi.reqPostTimeKeyWords(keywordPrefix)
        this.lenovoData = res.data
      } catch (error) {
        showNotify({ type: 'danger', message: '网络异常！' })
        return 'failed'
      }
    },
    // 获取热门搜索数据
    async getHotData() {
      try {
        const res = await searchApi.reqGetHotKeyWords()
        this.hotData = res.data
      } catch (error) {
        showNotify({ type: 'danger', message: '网络异常！' })
        return 'failed'
      }
    },
    // 重置搜索数据
    resetSearchData() {
      this.searchData = {
        directlyList: [],
        categoryL1List: []
      }
    },
    // 重置实时联想数据
    resetTimeData() {
      this.lenovoData = []
    },
    // 重置热门搜索数据
    resetHotData() {
      this.hotData = {
        hotKeywordVOList: []
      }
    }
  },
  getters: {
    // 热门搜索数据
    hotKeywordList: (state) => state.hotData.hotKeywordVOList || [],
    // 分类数据列表
    categoryList: (state) => state.searchData.categoryL1List || [],
    // 搜索到的商品数据列表
    searchGoodsData: (state) => state.searchData.directlyList || []
  }
})

export default useSearchStore
